package userFileModuleApi

import (
	"KumquatDrivesServices/common/res"
	"KumquatDrivesServices/enums"
	"KumquatDrivesServices/global"
	"KumquatDrivesServices/model"
	"KumquatDrivesServices/utils"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
)

type getAllFolderRequest struct {
	FolderId               model.SnowflakeIdType   `form:"folderId" binding:"required"`
	SelectedFileOrFolderId []model.SnowflakeIdType `form:"selectedFileOrFolderId"`
}

func (UserFileModuleApi) GetAllFolder(c *gin.Context) {
	var req getAllFolderRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		logrus.Errorf("GetAllFolder err: %v", err)
		res.FailWithCode(res.PARAM_ERR, c)
		return
	}
	logrus.Infof("req: %v", req.SelectedFileOrFolderId)
	userID := utils.GetUserId(c)
	var fileModel []model.FileModel
	query := global.DB.Where("file_pid=? and user_id=? and is_folder=? and del_flag=?",
		req.FolderId, userID, enums.Folder, enums.Normal)
	if len(req.SelectedFileOrFolderId) > 0 {
		//验证排除的文件夹是否属于当前用户
		var userOwnedIds []model.SnowflakeIdType
		err := global.DB.Model(&model.FileModel{}).
			Select("id").
			Where("id IN (?) AND user_id = ?", req.SelectedFileOrFolderId, userID).
			Pluck("id", &userOwnedIds).Error
		if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
			logrus.Errorf("Failed to validate SelectedFileOrFolderId ownership: %v", err)
			res.FailWithCode(res.SYS_ERR, c)
			return
		}
		if len(userOwnedIds) > 0 {
			query = query.Where("id not in (?)", userOwnedIds)
		}
	}
	if err := query.Find(&fileModel).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		logrus.Errorf("GetAllFolder err: %v", err)
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	res.OkWithData(fileModel, c)
}
